package com.baomidou.ant.service.impl;

import com.baomidou.ant.entity.PvpRecord;
import com.baomidou.ant.entity.PvpRoom;
import com.baomidou.ant.entity.User;
import com.baomidou.ant.mapper.PvpRoomMapper;
import com.baomidou.ant.service.IPvpRecordService;
import com.baomidou.ant.service.IPvpRoomService;
import com.baomidou.ant.service.IUserService;
import com.baomidou.ant.vo.Request.UserIdRequestVo;
import com.baomidou.ant.vo.Response.AllConnectUserVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2021-03-24
 */
@Service(value = "pvpRoomService")
public class PvpRoomServiceImpl extends ServiceImpl<PvpRoomMapper, PvpRoom> implements IPvpRoomService {
    @Autowired
    private IPvpRoomService pvpRoomService;
    @Autowired
    private IPvpRecordService pvpRecordService;
    @Autowired
    private IUserService userService;

    @Override
    public PvpRoom queryByUserId(Integer userId) {
        QueryWrapper<PvpRoom> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<PvpRoom> pvpRoomList=list(queryWrapper);
        return pvpRoomList.get(0);
    }

    @Override
    public IPage<AllConnectUserVo> listConnectUser(UserIdRequestVo vo) {
        IPage<PvpRoom> roomIPage=new Page<>(vo.getDisplayStart(),vo.getDisplayLength());
        //User user=userService.getById(userId);
        //得到所有连接上的用户,不包括自己
        QueryWrapper<PvpRoom> pvpRoomQueryWrapper=new QueryWrapper<>();
        pvpRoomQueryWrapper.eq("connect_status","1");
        pvpRoomQueryWrapper.ne("user_id",vo.getUserId());
        //得到分页结果
        IPage<PvpRoom> iPage=page(roomIPage,pvpRoomQueryWrapper);
        if(roomIPage.getRecords().size()<=0){
            return null;
        }
        return iPage.convert(pvpRoom -> {
            PvpRecord record=pvpRecordService.getByUserId(pvpRoom.getUserId());
            AllConnectUserVo connectUserVo=new AllConnectUserVo();
            User user=userService.getById(record.getUserId());
            BeanUtils.copyProperties(record,connectUserVo);
            connectUserVo.setSex(user.getSex());
            connectUserVo.setUserName(user.getUsername());
            connectUserVo.setUserId(user.getId());
            return connectUserVo;
        });
    }
}
